package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.Tools;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/5 0005.
 */
public class ChangeAddressActivity extends BaseActivity {


    public static final String ADDRESS_TEXT = "address";
    public static final String ADDRESS = "address_info";
    public static final String EMAIL = "email_info";
    private static final int RESULT_ADDRESS = 1001;

    /*输入地址*/
    private EditText mEtInput;
    /*清除文本*/
    private ImageView mIvClean;
    /*用户信息*/
    private User user;
    private int flag;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_address);

        initView();

        initData();

        setHeader();

        setListener();

    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(title);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mEtInput = (EditText) findViewById(R.id.et_address_input);
        mIvClean = (ImageView) findViewById(R.id.iv_address_text_clean);
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //根据uid从数据库获取用户信息
        int userid = CacheUtils.getIntData(ChangeAddressActivity.this, Constants.LOGIN_UID, 0);
        user = UserDaoImpl.getIntance(ChangeAddressActivity.this).findByQuery(userid);

        Intent intent = getIntent();
        flag = intent.getIntExtra("flag", 0);
        title = null;
        String input = null;
        if (flag != 0) {
            if (flag == Constants.PERSONAL_ADDRESS_INFO) {
                title = getResources().getString(R.string.personal_info_address);
                input = intent.getStringExtra(ADDRESS);
                mEtInput.setHint(R.string.change_address_hint);
            } else if (flag == Constants.PERSONAL_EMAIL_INFO) {
                title = getResources().getString(R.string.personal_info_email);
                input = intent.getStringExtra(EMAIL);
                mEtInput.setHint(R.string.change_email_hint);
            }
        }

        if (!TextUtils.isEmpty(input)) {
            mEtInput.setText(input);
            mIvClean.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //左边返回按钮的点击
        setLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //提交数据
                commit();
            }
        });

        //EditText的文本改变监听器
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                //设置清理文本的控件显示
                String inputInfo = mEtInput.getText().toString().trim();
                if (TextUtils.isEmpty(inputInfo)) {
                    mIvClean.setVisibility(View.GONE);
                } else {
                    mIvClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        //删除文本
        mIvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputInfo = mEtInput.getText().toString().trim();
                if (!TextUtils.isEmpty(inputInfo)) {
                    mEtInput.setText("");
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            commit();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }

    /**
     * 提交数据sdfsfd
     */
    private void commit() {
        final String inputResult = mEtInput.getText().toString().trim();
        if (flag == Constants.PERSONAL_ADDRESS_INFO) {
            if (TextUtils.isEmpty(inputResult)) {
                MyToast.show(ChangeAddressActivity.this, "地址不能为空");
            } else {
                commitData(inputResult);
            }
        } else if (flag == Constants.PERSONAL_EMAIL_INFO) {
            if (!TextUtils.isEmpty(inputResult)) {
                //检查是否是邮箱
                boolean isEmail = Tools.isEmail(inputResult);
                if (isEmail) {
                    commitData(inputResult);
                } else {
                    MyToast.show(ChangeAddressActivity.this, "请输入正确的邮箱");
                }
            } else {
                commitData(inputResult);
            }
        }
    }

    /**
     * 提交数据
     *
     * @param inputResult
     */

    private void commitData(final String inputResult) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", user.userid);
        maps.put("headurl", user.headurl);
        maps.put("sex", user.sex);
        maps.put("nickname", user.nickname);
        maps.put("phone", user.phone);
        maps.put("easemobsaccount", user.easemobsaccount);
        maps.put("easemobspassword", user.easemobspassword);
        if (flag == Constants.PERSONAL_ADDRESS_INFO) {
            maps.put("address", inputResult);
            maps.put("mailbox", user.mailbox);
        } else if (flag == Constants.PERSONAL_EMAIL_INFO) {
            maps.put("address", user.address);
            maps.put("mailbox", inputResult);
        }

        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_UPDATE_USERINFO, maps, MyHttp.POST, ChangeAddressActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

                //提交成功后将地址更新至数据库
                if (flag == Constants.PERSONAL_ADDRESS_INFO) {
                    user.address = inputResult;
                } else if (flag == Constants.PERSONAL_EMAIL_INFO) {
                    user.mailbox = inputResult;
                }
                UserDaoImpl.getIntance(ChangeAddressActivity.this).updata(user);

                //返回地址结果
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
            }
        });
    }
}
